<template>
  <view class="g-select-layout">
    <view>
      <button class="button " type="primary" @click="onOpenSelect">选择商品</button>
    </view>
    <uni-popup ref="popup" type="bottom" @change="onPopupChange">
      <view class="g-select bg-white">
        <view class="text-green" style="font-size:3.6rem;padding: .5rem 1rem;height: 6rem;line-height: 6rem;"
          @click="close(true)">
          <text class="cuIcon-back margin-right"></text> 选择商品
        </view>
        <view class="g-select-top bg-white padding">
          <view class="cu-form-group form-item-inline" style="width:55vw;padding: 1rem 0;">
            <view class="cu-form-group" style="padding: 0;">
              <uni-easyinput primaryColor="#38c09e" style="width:25vw;" suffixIcon="search" ref="search" clearable
                Trim="both" v-model="searchVal" placeholder="请输入条码/商品名/助记码" @confirm="willOnSearch"></uni-easyinput>
              <button class="button margin-left g-search " @click="onSearch" confirm-type="send"
                @confirm="onSearch">搜索</button>
            </view>
            <button class="button margin-left " @click="selectionAll">选择当前页</button>
            <button class="button margin-left " @click="close()">确认</button>
          </view>
        </view>
        <view class="g-select-centent">

          <view class="g-select-left padding">
            <gtree ref="xyTree" v-if="defaultSrvIsTree&&defaultSrvIsTree.pKey&&defaultSrvIsTree.pKey.no_col"
              :treeData="treeData"
              :replaceFields="{ children: 'children', key:defaultSrvIsTree.pKey.no_col, name:defaultSrvIsTree.pKey.key_disp_col}"
              @cnecked="treeChecked" @afterTreeInit="treeChecked"></gtree>
            <!-- <view v-for="(item,inde) in listData" :key="inde">{{JSON.stringify(item)}}</view> -->
          </view>
          <view class="g-select-right padding">
            <uni-table class="show-y-scroll-bar" rowKey="goods_barcode" ref="table" border stripe emptyText="暂无更多数据"
              type="selection" @selection-change="selectionChange">
              <!-- 表头行 -->
              <uni-tr>
                <uni-th align="center" v-for="(headCol,index) in goodsHeader" :key="index">{{headCol.label}}</uni-th>
              </uni-tr>
              <!-- 表格数据行 -->
              <uni-tr :keyValue="dataRow.goods_barcode" :disabled="dataRow.disabled"
                v-for="(dataRow,index) in goodsData.data" :key="index">
                <uni-td v-for="(headCol,i) in goodsHeader" :key="i">{{dataRow[headCol.columns]}}</uni-td>
              </uni-tr>

            </uni-table>
            <rpaging :inpage="goodsData.page ? goodsData.page : {pageNo: 1, rownumber: 999}"
              @on-page-change="onpagintion"></rpaging>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import gtree from '@/components/g-tree-select/g-tree-select.vue'
  import rpaging from '@/components/bx-pagination/bx-pagination.vue'
  export default {
    name: "g-batch-select",
    components: {
      gtree,
      rpaging
    },
    data() {
      return {
        searchVal: "",
        searchFocus: true,
        showLayout: false,
        configLoaded: false,
        listData: [],
        listpage: {
          pageNo: 1,
          rownumber: 999
        },
        serviceV2: null,
        treeData: [],
        treeBuild: false,
        goodsCondition: "",
        goodsData: {},
        goodsService: "srvretail_goods_info_check_select",
        goodsV2: null,
        goodsV2Load: false,
        selectedIndexs: [],
        selectIds: [],
        hasSelected: []
      };
    },
    computed: {
      searchFocusRun: {
        get: function() {
          return this.searchFocus
        },
        set: function() {
          this.searchFocus = true
        }
      },
      selectedDatasRun: function() {
        let self = this
        let index = this.selectedIndexs
        let data = self.deepClone(self.goodsData.data)
        let checkedData = self.selectedIndexs.map(i => data[i])
        return checkedData || []
      },
      goodsHeader: function() {
        let cols = this.goodsV2 ? this.goodsV2.srv_cols : []
        cols = cols.filter((item) => item.in_list == 1)
        let res = []
        let confHeader = this.custGridHeader || []
        if (confHeader && confHeader.length > 0) {
          for (let col of confHeader) {
            for (let v2col of cols) {
              if (col == v2col.columns) {
                res.push(v2col)
              }
            }
          }

        } else {
          res = cols
        }
        return res || []
      },
      defaultSrvIsTree: function() {
        let isTree = false
        let cfg = this.serviceV2
        if (cfg && cfg.hasOwnProperty('is_tree') && cfg.is_tree) {
          isTree = cfg.is_tree
          return {
            isTree: isTree,
            pKey: {
              no_col: cfg.no_col,
              parent_no_col: cfg.parent_no_col,
              key_disp_col: cfg.key_disp_col
            }
          }
        } else {
          return isTree
        }

      }

    },
    props: {
      mainService: {
        type: String,
      },
      servie: {
        type: String,
        default: ""
      },
      isTree: {
        type: Boolean,
        default: false
      },
      condition: {
        type: Array,
        default: function() {
          return []
        }
      },
      childPkey: {
        type: Object,
        default: function() {
          return null
        }
      },
      searchColumns: {
        type: Array,
        default: function() {
          return ["goods_barcode", "goods_name", "mnemonic_code"]
        }
      },
      initSelectedData: Array
    },
    methods: {
      treeChecked(e) {
        console.log("treeChecked", e)
        this.goodsCondition = e ? e.key : ""
        this.getRightListData(1)
      },
      willOnSearch() {
        setTimeout(() => {
          this.$nextTick(() => {
            console.log("willOnSearch", this.searchVal)
            this.getRightListData(1)
          })
        }, 200)
      },
      onSearch() {
        console.log("onSearch")
        // this.showLayout = true
        // this.$refs.popup.open('bottom')
        this.getRightListData(1)
      },
      onPopupChange(e) {
        if (e.show === true) {
          uni.hideLoading()
        }
      },
      onOpenSelect() {
        uni.showLoading({

        })
        this.selectIds = []
        console.log("onSearch")
        this.showLayout = true
        this.$refs.popup.open('bottom')
      },
      close(forceClose = false) {
        this.selectIds = []
        if (forceClose === true || this.selectedIndexs.length > 0) {
          this.showLayout = false
          this.$emit("on-select-change", this.selectedDatasRun)
          this.$refs.popup.close()
        } else {
          uni.showToast({
            title: '未选中商品！',
            icon: 'none'
          })
        }

      },
      getPageConfig() {
        let self = this
        let pageType = "selectlist"
        this.page = {
          pageNo: 1,
          rownumber: 20
        }
        if (this.configLoaded) {
          this.getListData()
        } else {
          this.getServiceV2(self.servie, 'select', pageType).then((res) => {
            this.serviceV2 = res
            this.configLoaded = true
            this.getListData()
            this.getRightListV2()
          })
        }

      },
      getRightListV2() {
        let self = this
        if (!self.goodsV2Load) {
          self.getServiceV2(self.goodsService, 'select', 'selectlist').then((res) => {
            self.goodsV2 = res
            self.goodsV2Load = true
            self.getRightListData()
          })
        } else {
          self.getRightListData()
        }

      },
      getRightListData(pageNo) {
        let cond = this.goodsCondition ? [{
          colName: "classify_path",
          ruleType: "like",
          value: `/${this.goodsCondition}/`
        }] : [];
        if (['srvretail_issue_add','srvretail_loss_reporting_add'].includes(this.mainService)) {
          cond.push({
            colName: 'goods_stock',
            ruleType: "ne",
            value: 0
          })
        }

        // let cond = this.goodsCondition ? [{colName:"goods_classify",ruleType:"eq",value:this.goodsCondition}] : []
        let relation = this.buildSearchRelationCondition(this.searchVal, this.searchColumns)
        let req = this.selectRequestObjs(this.goodsService, cond, null, relation)
        // delete this.listpage.total
        let page = this.goodsData.hasOwnProperty('page') ? this.deepClone(this.goodsData.page) : {
          pageNo: 1,
          rownumber: 10
        }
        delete page.total

        if (pageNo) {
          page.pageNo = pageNo
        }
        req['page'] = page
        if (this.goodsV2Load) {
          this.goodsData = {
            data: []
          }
          this.$fetch('select', this.goodsService, req).then((res) => {
            let selectIndex = []
            if (this.selectIds.length > 0) {
              this.selectedIndexs = []
              res.data.forEach((item, index) => {
                if (this.selectIds.find(id => item.goods_barcode && item.goods_barcode === id)) {
                  selectIndex.push(item)
                }
              })
            } else {
              // this.$refs.table.clearSelection()
            }
            let goodsData = this.deepClone(res)
            let selectedIndexs = []
            let defaultSelecte = []
            if (Array.isArray(this.initSelectedData) && this.initSelectedData.length > 0 && Array.isArray(goodsData
                .data) && goodsData.data.length > 0) {
              goodsData.data = goodsData.data.map((item, index) => {
                if (this.initSelectedData.find(e => e.goods_barcode && e.goods_barcode === item
                    .goods_barcode)) {
                  item.disabled = true
                  defaultSelecte.push(item)
                } else {
                  item.disabled = false
                }
                return item
              })
            }
            this.goodsData = goodsData
            // this.$refs.table.clearSelection()

            this.$nextTick(() => {
              if (Array.isArray(selectIndex) && selectIndex.length > 0) {
                this.$refs?.table?.toggleRowSelection(selectIndex, true)
              }
              if (Array.isArray(defaultSelecte) && defaultSelecte.length > 0) {
                this.$refs?.table?.toggleRowSelection(defaultSelecte, true, true)
              }
            })

          })

        }
      },
      getListData(pageNo, type) {
        let self = this
        let srv = self.servie
        let cond = []
        let listType = type || 'swipe'
        let req = this.selectRequestObjs(srv, cond, null)
        delete this.listpage.total
        req["page"] = this.listpage ? this.listpage : {
          pageNo: 1,
          rownumber: 20
        }
        if (pageNo) {
          req.page.pageNo = pageNo
        }
        if (this.configLoaded) {
          this.$fetch('select', srv, req).then((res) => {
            if (res.success) {
              if (pageNo !== 1 && pageNo !== null && pageNo !== undefined && listType == 'swipe') {
                this.listData = this.listData.concat(res.data)
              } else {
                this.listData = []
                this.listData = res.data
              }
              self.$set(self.listpage, 'pageNo', res.page.pageNo)
              self.$set(self.listpage, 'rownumber', res.page.rownumber)
              self.$set(self.listpage, 'total', res.page.total)
              if (res.page.pageNo * res.page.rownumber < res.page.total) {
                self.more = "more"
              } else {
                self.more = "noMore"
              }
              if (!self.treeBuild) {
                self.generateOptions(self.listData)
              }
              // self.triggered = false
            }
          })

        }

      },
      // 开始递归方法
      generateOptions(params, checked, expand) {
        console.log(params, "params是什么？？？");
        console.log(checked, "checked是什么？？？");

        console.log(expand, "expand是什么？？？")
        let self = this
        let result = []
        let list = params.filter(item => item)
        let nodeKey = self.defaultSrvIsTree.pKey.no_col
        let nodeLabel = self.defaultSrvIsTree.pKey.key_disp_col
        for (const param of list) {
          if (param.parent_no == null || param.parent_no == '' || param.parent_no == undefined) { // 判断是否为顶层节点
            let children = self.deepClone(param)
            children['label'] = children[nodeLabel]
            children['children'] = self.getchilds(children[nodeKey], list) // 获取子节点
            result.push(children)
          }
        }
        console.log(result, "什么是result--")
        self.$set(self, "treeData", result)
        self.treeBuild = true
        // self.$set(t,'_treeData',result.map((item) => item))
        // t['expandedKeys'] = []
        // t['checkStrictly'] = false
        // t['checkedKeys'] =[]
        // update 根据编号递归 特类型的选中项
        //  if(self.pageType == 'update'){
        // for(let funCol of self.authFunListdata){
        //   for(let checkNode of self.roleFunData){
        // 	if(funCol[nodeKey] == checkNode[nodeKey] && t.terminal_type == funCol['terminal_type']){
        // 	   t.checkedKeys.push(checkNode[nodeKey])
        // 	}
        //   }
        // }
        //  }
      },
      getchilds(nodeKey, array) {
        let self = this
        let nKey = self.defaultSrvIsTree.pKey.no_col
        let nLabel = self.defaultSrvIsTree.pKey.key_disp_col
        const childs = []
        for (const arr of array) { // 循环获取子节点
          if (arr['parent_no'] === nodeKey) {
            childs.push(self.deepClone(arr))
          }
        }
        for (const child of childs) { // 获取子节点的子节点
          const childscopy = self.getchilds(child[nKey], array) // 递归获取子节点

          child['label'] = child[nLabel]
          child['children'] = childscopy
        }
        return childs
      },
      onpagintion(e) {
        console.log("onpagintion", e)
        this.getRightListData(e, "pagintion")
      },
      selectionChange(e) {
        // let res = this.goodsData

        // if(Array.isArray(this.initSelectedData)&&this.initSelectedData.length>0&&Array.isArray(res.data)&&res.data.length>0){
        //   let ids = []
        //   res.data.forEach((item,index)=>{
        //     if(this.initSelectedData.find(e=>e.goods_barcode&&e.goods_barcode===item.goods_barcode)){
        //       ids.push(index)
        //     }
        //   })
        //   debugger
        //   this.$refs?.table?.toggleRowSelection(ids,true)
        // }

        this.selectedIndexs = e.detail.index
        if (e.detail.index.length > 0) {
          this.selectIds = []
          e.detail.index.forEach(index => {
            this.selectIds.push(this.goodsData.data[index].goods_barcode)
          })
        }
      },
      selectionAll() {
        if (this.selectedIndexs.length === this.goodsData.data.length) {
          this.$refs.table.clearSelection()
        } else {
          this.$refs.table.selectionAll()
        }
      },
    },
    created() {

      this.treeData = this.$store?.state?.$classifyList || []
      const goodsList = this.$store?.state?.$goodsList
      if (Array.isArray(goodsList) && goodsList.length > 0) {
        this.goodsData = {
          data: goodsList.slice(0, 10),
          page: {
            total: goodsList.length,
            rownumber: 10,
            pageNo: 1
          }
        }
      }

    },
    watch: {
      "showLayout": {
        deep: true,
        handler: function(nawVal, oldVal) {
          let self = this
          console.log("nawVal", nawVal)
          if (nawVal) {
            this.getPageConfig()
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .g-select {
    height: calc(100vh - 6rem);
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .margin-left {
      margin-left: 2rem;
    }

    width: 100vw;

    .g-select-top {
      height: 12rem;
      width: 100vw;
      display: flex;
      align-items: center;
    }

    .g-select-centent {
      // height: calc(100vh - 12rem);
      flex: 1;
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      overflow: hidden;
      overflow-y: scroll;

      .g-select-left {
        width: 25vw;
      }

      .g-select-right {
        width: 75vw;
        background-color: #f2f2f2;
        overflow-y: hidden;
        display: flex;
        flex-direction: column;
      }
    }

    // <veiw class="g-select-centent">
    // 	<veiw class="g-select-left"></veiw>
    // 	<veiw class="g-select-right"></veiw>
    // </veiw>
  }
</style>
